<template>
  <div id='wrap'>
    <h1>effectScope案例4</h1>
    <div v-if="isShow">
        <h3>countA:{{ abc.countA }}</h3>
        <h3>countB:{{ abc.countB }}</h3>
        <button @click="abc.incrementA">incrementA</button>
        <button @click="abc.incrementB">incrementB</button>
        <button @click="stopScope">销毁作用域</button>
    </div>
    <hr>
    <div v-show="isStopped">
        <h3>计数器的作用已经销毁成功</h3>
    </div>
  </div>
</template>

<script lang='ts'>
export default {
  name: 'scu10',
}
</script>

<script lang='ts' setup>
import { ref,type Ref,effectScope,EffectScope,onScopeDispose } from 'vue'
interface classA{
    countA:Ref<number>
    countB:Ref<number>
    incrementA:()=>void
    incrementB:()=>void
}
let scope:EffectScope
const isShow:Ref<boolean>=ref(false)
console.log(isShow);
function setupScope():Promise<classA>{
    scope=effectScope()
    return new Promise((resolve) => {
        let timer1:ReturnType<typeof setInterval>
        let timer2:ReturnType<typeof setInterval>
        scope.run(()=>{
            const countA=ref(1)
            const countB=ref(2)
            const incrementA=()=>{
                timer1=setInterval(()=>{
                    countA.value++
                },100)
            }
            const incrementB=()=>{
                timer2=setInterval(()=>{
                    countB.value++
                },100)
            }
            onScopeDispose(()=>{
                clearInterval(timer1)
                clearInterval(timer2)
                console.log('该作用域已经停止,清理资源');
            })
            resolve({countA,countB,incrementA,incrementB})
        })
    })
}
let abc:classA
const initScope=async()=>{
    abc=await setupScope()
    console.log(abc.countA.value);
    isShow.value=true
}
const isStopped=ref(false)
function stopScope(){
    if(scope){
        scope.stop()
        isStopped.value=true
    }
}
initScope()
</script>

<style scoped lang='scss'>

</style>